package com.pet.server.ext.action.request;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.pet.server.ext.ActionBase;
import com.pet.server.ext.ApiError;
import com.pet.server.ext.BeanToJson;
import com.pet.server.ext.Result;
import com.pet.server.ext.constants.BaseAttribute;
import com.pet.server.ext.data.Option;
import com.pet.server.ext.data.Page;
import com.pet.server.ext.data.RequestInfo;
import com.pet.server.ext.service.UserService;
import com.pet.server.ext.util.Parameters;

/**
 * 我参与的投票
 * @author admin
 *
 */
public class Myvote extends ActionBase{

	public Integer startIndex,itemCount,user_id;
	public String queryString,state;
	public Page page;
	public Myvote(){
		 needCheckAuth =true;
	}
	
	@Override
	public void initParameters(Parameters params) throws ApiError {
		parseToParameter(params);
		itemCount = p.itemCount==0?10:p.itemCount;
		page = new Page(p.startIndex, itemCount,p.queryString);
		state = params.getFieldValue("state");
	}
	
	@Override
	public Result invokeService() throws ApiError {
		UserService userService = new UserService();
		userService.searchRequestInfo4Myvote(page, user.user_id);
		JSONArray array = new JSONArray();
		for(Object r:page.getList()){
              RequestInfo req = (RequestInfo)r;	
              JSONObject o = BeanToJson.beanToJson(req,"reply_id");
              if(BaseAttribute.diaoc.equals(req.type)){
                  List<Option> options=userService.queryOptionByRequestId(req.id);
                  o.put("options", BeanToJson.listTojson(options));
           	      String isvote=userService.isVote(user.user_id, req.id);
                  o.put("is_vote", isvote);       
           	      o.put("vote_count", voteCount(options));
              }
              array.add(o);
		}
		Result result = new Result();
        result.setPage(page,array);
	    return result;
	}

	private Integer voteCount(List<Option> options){
		Integer vote_count=0;
		for(Option o:options){
			vote_count+=o.getTimes();
		}
		return vote_count;
	}


}
